package com.woniuxy.pxxt.controller;


import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;

import com.woniuxy.pxxt.common.enums.TrainEnrollFormStatus;
import com.woniuxy.pxxt.common.result.Result;
import com.woniuxy.pxxt.common.result.ResultCodeEnum;
import com.woniuxy.pxxt.utils.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@CrossOrigin
public class AuthController extends BaseController{

	public
	//图片生成
	@Autowired
	Producer producer;

	@GetMapping("/captcha")
	public Result captcha() throws IOException {

		//验证码存入redis时的key值,用于用户登陆时,再从redis中查找验证码是否正确
		String key = UUID.randomUUID().toString();
		//随机生成的验证码字符
		String code = producer.createText();

		BufferedImage image = producer.createImage(code);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", outputStream);

		BASE64Encoder encoder = new BASE64Encoder();
		String str = "data:image/jpeg;base64,";

		String base64Img = str + encoder.encode(outputStream.toByteArray());


		//把图片验证验证码的存入redis中, key:为captcha+uudi ,value为:随机生成的字符, 有效时间为2min
		//redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
		redisUtil.set(key,code,100);
		//返回base64格式的图片验证码
		return Result.ok(
				MapUtil.builder()
						.put("token", key)
						.put("captchaImg", base64Img)
						.build()

		).message("获取验证码成功");
	}

	@RequestMapping("/401")
	public Result AuthentionFail(ServletRequest request, ServletResponse response){
		return Result.build(null,ResultCodeEnum.NO_LOGIN).message("登录失效");
	}



}
